package com.cwj.user.fieter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cwj.common.domain.user;
import com.cwj.common.utils.utils;
import com.cwj.user.dao.userDao;
import lombok.Setter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Setter
public class userExists_filter implements Filter {
    private com.cwj.user.dao.userDao userDao;
    private ServletContext servletContext;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        userExists(servletResponse, filterChain, request, userDao, servletContext);
    }

    public static void userExists(ServletResponse servletResponse, FilterChain filterChain, HttpServletRequest request, userDao userDao, ServletContext servletContext) throws IOException, ServletException {
        Map<String, String> userByCookie = utils.GetUserByCookie(request.getCookies());
        Integer selectCount = userDao.selectCount(new QueryWrapper<user>().allEq(userByCookie));
        if(selectCount!=null&&selectCount>0) {
            filterChain.doFilter(request, servletResponse);
        }else {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendRedirect(servletContext.getAttribute("UserUrl") + "error.html");
        }
    }
}
